package com.wondertek.poms.core.service.impl;

import cn.hutool.core.convert.Convert;
import com.wondertek.poms.common.service.impl.ServiceImpl;
import com.wondertek.poms.core.service.ISellingPriceService;
import com.wondertek.poms.dao.po.SellingPrice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

/**
 * <p><b>PcProductRuleServiceImpl Description:</b> 售价 service层实现 </p>
 *
 * @author 窦再兴
 * <p><b>DATE</b> 2020-10-16 15:56:15</p>
 */
@Service
@Scope("prototype")
public class SellingPriceServiceImpl extends ServiceImpl<SellingPrice, Long> implements ISellingPriceService {

	@PersistenceContext
    public EntityManager entityManager;

	@Override
	public SellingPrice deleteLogic(Long id) {
		return null;
	}

	@Override
	public SellingPrice merge(SellingPrice model) {
		return null;
	}

	@Override
	public Page<SellingPrice> findAll(SellingPrice entity, int page, int rows, String sord, String sidx) {
		StringBuilder condition = sqlStringWhere(entity,sord,sidx);
		Object o = entityManager
				.createNativeQuery("select count(*) from ( " + condition.toString() + " ) a").getSingleResult();
		int count = Convert.toInt(o);
		Pageable pageable = getPageable(page - 1, rows, sord, sidx);

		if(count>0){
			Query query=entityManager.createNativeQuery(condition.toString(),SellingPrice.class);
			query.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
			query.setMaxResults(pageable.getPageSize());
			List<SellingPrice> list=query.getResultList();
			PageImpl<SellingPrice> result=new PageImpl<>(list,pageable,count);
			entityManager.close();
			return result;
		}
		entityManager.close();
		return Page.empty(pageable);
	}

	public StringBuilder sqlStringWhere(SellingPrice entity,String sord, String sidx){
		StringBuilder condidtion=new StringBuilder();
		String sql="select * from SELLING_PRICE where 1=1 ";
		condidtion.append(sql);

		if(entity.getSellingPriceNum()!=null){
			condidtion.append("and SELLING_PRICE_NUM= "+entity.getSellingPriceNum()+" ");
		}
		if(entity.getProductId()!=null){
			condidtion.append("and PRODUCT_ID= "+entity.getProductId()+" ");
		}

		condidtion.append("order by "+sidx+" "+sord);
		return condidtion;
	}
}